import base64
import time
import hashlib
import uuid
import requests
from Crypto.Cipher import AES
import codecs
session=requests.session()
import time

proxies= {
  "http": "http://127.0.0.1:7890",
  "https": "http://127.0.0.1:7890"
}
def pkcs5_pad(data: bytes) -> bytes:
    pad_len = 16 - len(data) % 16
    return data + bytes([pad_len] * pad_len)
def md5(str):
    return hashlib.md5(str.encode("utf-8")).hexdigest()
def md5_hash(s, substring=True):
    """
    对字符串进行MD5哈希并转为十六进制字符串
    substring=True时返回8-24位的子串（即16个字符）
    """
    if not s:
        return None
    try:
        md5 = hashlib.md5()
        md5.update(s.encode('utf-8'))
        hash_hex = md5.hexdigest()
        return hash_hex[8:24] if substring else hash_hex
    except Exception as e:
        print(f"MD5哈希失败: {e}")
        return None
def generate_udid():
    """
    生成_udid的完整逻辑
    """
    random_uuid = str(uuid.uuid4())
    udid = md5_hash(random_uuid)
    return udid
def get_flag(key, appid, udid, version, timestamp):
    parr = key + appid + udid + version + timestamp
    jiami1 = md5(parr)
    jiami2 = md5(jiami1)
    return jiami2
def aes_encrypt_to_base64(data: str, key: str) -> str:
    key_bytes = key.encode('utf-8')[:16]
    key_bytes = key_bytes.ljust(16, b'\x00')
    cipher = AES.new(key_bytes, AES.MODE_ECB)
    padded_data = pkcs5_pad(data.encode('utf-8'))
    encrypted = cipher.encrypt(padded_data)
    return base64.b64encode(encrypted).decode('utf-8')
def generate_webcode(_udid,_appid,_v,_version):
    """
    生成ZAKER应用的_webcode参数

    返回:
    生成的_webcode参数（20字符长度）
    """
    # 组合初始字符串
    initial_str = f"{_udid},,{_appid},{_v},{_version}".lower()
    # 连续2次MD5哈希
    result = initial_str
    for _ in range(3):
        result = hashlib.md5(result.encode()).hexdigest().lower()

        # 截断为20字符
    return result[:20]
def generate_mcode(appid, dev, udid, version):
    """生成MCODE参数"""
    # 拼接参数
    concatenated = appid + dev + udid + version

    # 转小写并添加固定盐值
    with_salt = concatenated.lower() + "IO2#!spopqd"

    # 三重MD5哈希
    hash1 = hashlib.md5(with_salt.encode('utf-8')).hexdigest()
    hash2 = hashlib.md5(hash1.encode('utf-8')).hexdigest()
    hash3 = hashlib.md5(hash2.encode('utf-8')).hexdigest()

    # 转大写并取前8位
    return hash3.upper()[:8]

# ================== 1. 构建str2内容 =========================
key = "WvT6dYtChFRdb7yKsearch"
_version = "9.08"
# _time ="1754468252"
_appid = "AndroidPhone"
_time = str(int(time.time()))
_v = "9.1.5"
_dev = "39"
# _udid = generate_udid()
_udid = "1fb67af59b5699a6"
print("_udid==>", _udid)
# 动态生成MCODE
# _mcode = generate_mcode(_appid, _dev, _udid, _v)
_mcode = "782ECE9C"
print("_mcode==>",_mcode)
_flag = get_flag(key, _appid, _udid, _version, _time)
print("_flag==>",_flag)
_webcode = generate_webcode(_udid.lower(),_appid.lower(),_v.lower(),_version.lower())
print("_webcode==>",_webcode)


str2 = f'''{{
    "bd_return_size":"71.5791",
    "bd_net_type":"wifi",
    "bd_return_time":"0.358",
    "bd_dtime":"{_time}",
    "list":[
        {{
            "local_ip":"",
            "url":"https://iphone.myzaker.com/zaker/interaction.php?_appid\\u003dAndroidPhone\\u0026_brand\\u003dRedmi\\u0026_clicode\\u003ddrkjeSEfcYDX1teOXihrCj2XzcFRNfVX8%2BYz4c8F97ou09PFuxwXRz5MiGDDPUNGhem0wpj6%2FrZjDz2db1S7FvanFsXVXzuSqDN0%2F9H5fXQboq5tdRLZNTtTWglt14Ow2up6UUUAOroimS1HlUPRnt%2FCQ4I%2BuQaYbMO3tBgfzppDreyPYJ3gJetESX4Iz9g%2F\\u0026_dev\\u003d39\\u0026_mcode\\u003d{_mcode}\\u0026_only_read\\u003dN\\u0026_os\\u003d13_23013RK75C\\u0026_os_name\\u003d23013RK75C\\u0026_udid\\u003d1fb67af59b5699a6\\u0026_v\\u003d9.1.5\\u0026_version\\u003d9.08\\u0026appType\\u003dnormal",
            "net_type":"wifi",
            "req_type":"local",
            "e_type":"2",
            "return_time":"3.23",
            "dtime":"1.75453683E9"
        }},
        {{
            "local_ip":"",
            "url":"https://iphone.myzaker.com/zaker/app_style.php?_appid\\u003dAndroidPhone\\u0026_brand\\u003dRedmi\\u0026_clicode\\u003ddrkjeSEfcYDX1teOXihrCj2XzcFRNfVX8%2BYz4c8F97ou09PFuxwXRz5MiGDDPUNGhem0wpj6%2FrZjDz2db1S7FvanFsXVXzuSqDN0%2F9H5fXQboq5tdRLZNTtTWglt14Ow2up6UUUAOroimS1HlUPRnt%2FCQ4I%2BuQaYbMO3tBgfzppDreyPYJ3gJetESX4Iz9g%2F\\u0026_dev\\u003d39\\u0026_flag\\u003d9f0369ff51876206a9b5dd33b6d91686\\u0026_mcode\\u003d{_mcode}\\u0026_only_read\\u003dN\\u0026_os\\u003d13_23013RK75C\\u0026_os_name\\u003d23013RK75C\\u0026_time\\u003d1754536856\\u0026_udid\\u003d1fb67af59b5699a6\\u0026_v\\u003d9.1.5\\u0026_version\\u003d9.08\\u0026appType\\u003dnormal\\u0026sign_arg\\u003dapp_style|_appid,_nudid,_udid,_uid,_version",
            "net_type":"wifi",
            "req_type":"local",
            "e_type":"2",
            "return_time":"3.26",
            "dtime":"1.75453683E9"
        }},
        {{
            "local_ip":"",
            "url":"https://iphone.myzaker.com/zaker/ar_data/ar_list.php?_appid\\u003dAndroidPhone\\u0026_brand\\u003dRedmi\\u0026_clicode\\u003drkjeSEfcYDX1teOXihrCj2XzcFRNfVX8%2BYz4c8F97ou09PFuxwXRz5MiGDDPUNGhem0wpj6%2FrZjDz2db1S7FvanFsXVXzuSqDN0%2F9H5fXQboq5tdRLZNTtTWglt14Ow2up6UUUAOroimS1HlUPRnt%2FCQ4I%2BuQaYbMO3tBgfzppDreyPYJ3gJetESX4Iz9g%2F\\u0026_dev\\u003d39\\u0026_mcode\\u003d{_mcode}\\u0026_only_read\\u003dN\\u0026_os\\u003d13_23013RK75C\\u0026_os_name\\u003d23013RK75C\\u0026_udid\\u003d1fb67af59b5699a6\\u0026_v\\u003d9.1.5\\u0026_version\\u003d9.08\\u0026appType\\u003dnormal",
            "net_type":"wifi",
            "req_type":"local",
            "e_type":"2",
            "return_time":"3.363",
            "dtime":"1.75453683E9"
        }}
    ]
}}'''
print(str2)
# ================== 2. 生成data_code(加密) =========================
key = "amJKJsirodlsd129"
data_code = aes_encrypt_to_base64(str2, key)
print(f"data_code：{data_code[:200]}")
# ================== 3. 请求接口 =========================
def app_net():
    url = "https://iphone.myzaker.com/urlcheck/app_net.php"
    headers = {
        "Host": "iphone.myzaker.com",
        "User-Agent": "okhttp/4.2.2"
    }
    params = {
        "_no_track": "Y"
    }
    data = {
        "data_code": data_code,
        "_os": "13_23013RK75C",
        "_icode": "d4dcd1df6253de3b",
        "_msa_oa_id": "d4dcd1df6253de3b",
        "_os_name": "23013RK75C",
        "_mcode": _mcode,
        "_net": "wifi",
        "_bsize": "1080_1920",
        "_only_read": "N",
        "appType": "normal",
        "_v": "9.1.5",
        "_udid": "1fb67af59b5699a6",
        "_dev": "39",
        "_appid": "AndroidPhone",
        "_android_id": "b9d0a4eaadbef9d1",
        "_version": "9.08",
        "_brand": "Redmi"
    }

    response = session.post(url, headers=headers, params=params, data=data,proxies=proxies)
    print(response.text)
    print(response.status_code)
def search_zaker(keyword="特朗普"):
    proxies = {
        'http': 'http://127.0.0.1:7890',
        'https': 'http://127.0.0.1:7890'
    }

    headers = {
        "Host": "search.myzaker.com",
        "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Android WebView\";v=\"138\"",
        "sec-ch-ua-mobile": "?1",
        "sec-ch-ua-platform": "\"Android\"",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Linux; Android 13; 23013RK75C Build/TKQ1.220905.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.179 Mobile Safari/537.36 ZAKER/9.1.5",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "appinfo": "zaker 9.1.5 androidphone",
        "X-Requested-With": "com.myzaker.ZAKER_Phone",
        "Sec-Fetch-Site": "none",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-User": "?1",
        "Sec-Fetch-Dest": "document",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }

    url = "https://search.myzaker.com/api/"


    params = {
        "_webcode": _webcode,
        "_flag": _flag,
        "_os": "13_23013RK75C",
        "sign_arg": "search|_appid,_udid,_uid,_version,keyword",
        "app_ids": "660,310000,13,9,4,11542,5,7,3,8,10530,14,11581,14733",
        "_os_name": "23013RK75C",
        "_mcode": _mcode,
        "_only_read": "N",
        "_clicode": "drkjeSEfcYDX1teOXihrCj2XzcFRNfVX8%2BYz4c8F97ou09PFuxwXRz5MiGDDPUNGhem0wpj6%2FrZjDz2db1S7FvanFsXVXzuSqDN0%2F9H5fXQboq5tdRLZNTtTWglt14Ow2up6UUUAOroimS1HlUPRnt%2FCQ4I%2BuQaYbMO3tBgfzppDreyPYJ3gJetESX4Iz9g%2F",
        "appType": "normal",
        "_v": _v,
        "_udid": _udid,
        "_appid": _appid,
        "_dev": _dev,
        "keyword": keyword,
        "full_arg": "_udid",
        "_version": _version,
        "_time": _time,
        "_brand": "Redmi"
    }

    response = session.get(url, headers=headers, params=params, proxies=proxies)
    print(response.status_code)
    decoded_text = codecs.decode(response.text, 'unicode_escape')
    return decoded_text


if __name__ == "__main__":
    app_net()
    result = search_zaker("特朗普")
    print(result)

    # 保存到文件
    with open("search_result.html", "w", encoding="utf-8") as f:
        f.write(result)
